#include "stdafx.h"
#include "Device\PortManager.h"

CPortManager::CPortManager()
{

}



CPortManager::~CPortManager()
{

}



CPortManager* CPortManager::GetInstance()
{
	static CPortManager instance;
	return &instance;
}



UINT16 CPortManager::AllocId(UINT16 pos)
{

	ASSERT(pos >0  &&  pos <= PORT_MAX_NUM);

	for (int i = 0; i < PORT_MAX_NUM; i++) {
		if (mIdPosMap[i] == 0) {
			mIdPosMap[i]  = pos;
			//mPorts[pos-1].CommitUpdate();

			return i+1;
		}
	}

	return 0;
}



CPort* CPortManager::GetPortAt(int pos)
{
	if (pos > 0 && pos < 7) {
		return &mPorts[pos - 1];
	}
	else {
		Print("Invalid pos-->\'Get port at %d\'", pos);
		return NULL;
	}
}



CPort* CPortManager::GetPortById(UINT id)
{
	//Print("Get port by id of %d", id);

	ASSERT(id >0  &&  id <= PORT_MAX_NUM);

	//Print("Id %d --- Pos %d", id, mIdPosMap[id-1]);
	return &mPorts[ mIdPosMap[id-1] -1];
}



void CPortManager::LoadConfig()
{
	SQLiteStatement* stmt  = CDBHelper::GetInstance().Query("port_config", "*");
	int  inx  = 0;
	UINT id  = 0;
	while (stmt->NextRow()) {
		Print("while %d", __LINE__);
		id  = stmt->ValueInt(1);
		if (id <= PORT_MAX_NUM) {
			mPorts[inx].mPos  = inx+1;
			mPorts[inx].SetId(stmt->ValueInt(1));
			mPorts[inx].mConfig.mNameId  = stmt->ValueInt(2);
			mPorts[inx].mConfig.mIsCameraOn  = stmt->ValueInt(3);
			mPorts[inx].mConfig.mIsRecordEnabled  = stmt->ValueInt(4);
			mPorts[inx].mConfig.mIsAutoWatchEnabled  = stmt->ValueInt(5);
			mPorts[inx].mConfig.mVol  = stmt->ValueInt(6);

			mIdPosMap[id-1]  = inx+1;
			inx++;						
		}
		else {
			Print("Load config that id too big");
			ASSERT(FALSE);
		}
	}

	delete stmt;

	Print("Id at pos %d %d %d %d %d %d", mPorts[0].GetId(), mPorts[1].GetId(), mPorts[2].GetId(),
										 mPorts[3].GetId(), mPorts[4].GetId(), mPorts[5].GetId()  );
	Print("Pos at id %d %d %d %d %d %d", mIdPosMap[0], mIdPosMap[1], mIdPosMap[2], mIdPosMap[3], mIdPosMap[4], mIdPosMap[5]);
}



void CPortManager::Reborn()
{
	for (int i = 0; i < PORT_MAX_NUM; i++) {
		mPorts[i].Reborn();
	}
}



UINT CPortManager::GetAlarmRecordVirginNumber()
{
	UINT cnt  = 0;
	for (int i = 0; i < PORT_MAX_NUM; i++) {
		if (mPorts[i].GetId() > 0) {
			cnt += mPorts[i].mAlarmRecord.GetVirginNumber();
		}		
	}

	return cnt;
}